package server;

import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;


public class ClientResponder extends Thread{
	private Queue<String> messages = new LinkedList<String>();
	private PrintWriter out;
	boolean working = true;
	
	public ClientResponder(PrintWriter out) {
		this.out = out;
	}
	
	@Override
	public void run() {
		while(working) {	//wysylamy wiadomosci poki zyjemy
			synchronized(messages) {
				if (messages.isEmpty())
					try {
						messages.wait();	//jak nie mamy co wyslac, to czekamy az bedzie co
					} catch (InterruptedException e) {
					}
				String str = messages.poll();
				System.out.println("Responder, poll & print: " + str);
				out.println(str); // and again
			}
		}
	}
	
	public void addToSend(String s) {	//dodajemy wiadomosc do wyslania
		System.out.println("Responder, to send: " + s);
		synchronized(messages) {
			messages.add(s);
			messages.notifyAll();
		}
	}
	
	public void die() {	//zabijamy watek
		synchronized(messages) {
			working = false;
			messages.notifyAll();
		}
	}
}